package com.bytech.comment.biz.service.emoticon.Impl;

import java.util.Date;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bytech.common.biz.entity.base.BaseResult;
import com.bytech.common.biz.entity.emoticon.Emoticon;
import com.bytech.comment.biz.mapper.emoticon.EmoticonMapper;
import com.bytech.comment.biz.service.emoticon.EmoticonService;
import com.bytech.common.biz.entity.emoticon.EmoticonDto;
import com.bytech.common.biz.entity.emoticon.EmoticonQuery;
import com.bytech.common.biz.enums.emoticon.EmoticonSourceEnum;
import com.bytech.common.biz.service.base.BasicServiceImpl;
import com.bytech.common.utils.StringUtils;

import org.springframework.stereotype.Service;

/**
 * @Author Zhao
 * @Create 2021-12-04
 */
@Service
public class EmoticonServiceImpl extends BasicServiceImpl<EmoticonMapper, Emoticon> implements EmoticonService {

    @Override
    public Page<EmoticonDto> pageByQuery(EmoticonQuery<Emoticon> emoticonQuery) {
        LambdaQueryWrapper<Emoticon> queryWrapper = buildQueryWrapper(emoticonQuery);
        page(emoticonQuery, queryWrapper);
        return emoticonQuery.translateRecordsTo(EmoticonDto.class);
    }

    @Override
    public BaseResult<?> toggleUsable(Long id) {
        Emoticon emoticon = getById(id);
        if (emoticon == null) {
            return BaseResult.error("表情不存在").build();
        }
        emoticon.setIsUsable(!emoticon.getIsUsable());
        emoticon.setModifyTime(new Date());
        updateById(emoticon);
        return BaseResult.success("修改成功").build();
    }

    @Override
    public BaseResult<?> doModifyEmoticonName(Long id, String name) {
        if (StringUtils.isBlank(name)) {
            return BaseResult.error("名称不能为空").build();
        }
        Emoticon emoticon = getById(id);
        if (emoticon == null) {
            return BaseResult.error("表情不存在").build();
        }
        emoticon.setName(name);
        emoticon.setModifyTime(new Date());
        updateById(emoticon);
        return BaseResult.success("修改成功").build();
    }

    private LambdaQueryWrapper<Emoticon> buildQueryWrapper(EmoticonQuery<Emoticon> emoticonQuery) {
        LambdaQueryWrapper<Emoticon> queryWrapper = new LambdaQueryWrapper<>();
        if (emoticonQuery == null) {
            return queryWrapper;
        }
        if (!StringUtils.isBlank(emoticonQuery.getCode())) {
            queryWrapper.eq(Emoticon::getEmoticonFrom, EmoticonSourceEnum.of(emoticonQuery.getCode()).getCode());
        }
        if (!StringUtils.isBlank(emoticonQuery.getName())) {
            queryWrapper.like(Emoticon::getName, emoticonQuery.getName());
        }
        if (emoticonQuery.getUsable() != null) {
            queryWrapper.eq(Emoticon::getIsUsable, emoticonQuery.getUsable());
        }
        return queryWrapper;
    }
}
